import 'package:flutter/material.dart';

class CustomSearchField extends StatefulWidget {
  final Icon prefixIcon;
  final double borderRadius;
  final double verticalPadding;
  final String hintText;
  final Function(String)? onTextChanged;

  const CustomSearchField({
    Key? key,
    this.prefixIcon = const Icon(
      Icons.search,
      size: 22,
    ),
    this.borderRadius = 30.0,
    this.verticalPadding = 5.0,
    this.hintText = '请输入搜索内容',
    this.onTextChanged,
  }) : super(key: key);

  @override
  State<CustomSearchField> createState() => _CustomSearchFieldState();
}

class _CustomSearchFieldState extends State<CustomSearchField> {
  final TextEditingController _controller = TextEditingController();
  bool _hasText = false;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      setState(() {
        _hasText = _controller.text.isNotEmpty;
      });
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: _controller,
      onChanged: widget.onTextChanged,
      style: const TextStyle(fontSize: 15), // 调整字体大小
      decoration: InputDecoration(
        hintText: widget.hintText,
        prefixIcon: Padding(
          padding: EdgeInsets.all(widget.verticalPadding),
          child: widget.prefixIcon,
        ),
        suffixIcon: _hasText
            ? IconButton(
                icon: const Icon(Icons.clear, size: 20, color: Colors.grey),
                onPressed: () {
                  _controller.clear();
                  if (widget.onTextChanged != null) {
                    widget.onTextChanged!('');
                  }
                  setState(() {
                    _hasText = false;
                  });
                },
              )
            : null,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(widget.borderRadius),
          borderSide: const BorderSide(
            color: Colors.grey, // 边框颜色
          ),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(widget.borderRadius),
          borderSide: const BorderSide(
            color: Colors.grey,
          ),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(widget.borderRadius),
          borderSide: const BorderSide(
            color: Colors.grey,
          ),
        ),
        filled: true,
        isDense: true, // 紧凑模式
        fillColor: Colors.white,
        contentPadding: EdgeInsets.symmetric(vertical: widget.verticalPadding),
      ),
    );
  }
}
